'use client';

import { queryRoleMenusById } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import type { IMenu, IRole } from '@/interfaces';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function MenusRoleAdminPage({
  source,
  translatedFields,
}: {
  source: IRole;
  translatedFields: PrefixedTTranslatedFields<'roleAdminPage'>;
}) {
  const queryRoleMenusByIdQuery = useQuery(
    ['/roles', source.id, '/menus'],
    async (context) => {
      return (await queryRoleMenusById({
        id: context.queryKey[1] + '',
      })) as IMenu[];
    },
  );

  if (queryRoleMenusByIdQuery.data) {
    const data = queryRoleMenusByIdQuery.data;

    return (
      <div className="card">
        <div className="card-header bg-transparent text-secondary">
          <i className="bi bi-list me-2"></i>
          {translatedFields.properties.menu}
        </div>
        <div className="card-body">
          <div className="table-responsive">
            <table className="table align-middle">
              <thead>
                <tr className="text-nowrap">
                  <th scope="col" className="">
                    ID
                  </th>
                  <th scope="col" className="">
                    {translatedFields.properties.name}
                  </th>
                  <th scope="col" className="">
                    {translatedFields.properties.path}
                  </th>
                  <th scope="col" className="">
                    {translatedFields.properties.sort}
                  </th>
                  <th scope="col" className="">
                    {translatedFields.properties.type}
                  </th>
                  <th scope="col" className="">
                    {translatedFields.properties.mainMenu}
                  </th>
                </tr>
              </thead>
              <tbody>
                {data.map((item) => {
                  return (
                    <tr key={item.id} className="text-nowrap">
                      <td>{item.id}</td>
                      <td>{item.name}</td>
                      <td>{item.path}</td>
                      <td>{item.sort}</td>
                      <td>{translatedFields.enums.menuType[item.menuType]}</td>
                      <td>{item.type === 1 ? 'true' : 'false'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {data.length === 0 && <Nodata />}
        </div>
      </div>
    );
  }

  if (queryRoleMenusByIdQuery.error) {
    return <Alert type="error" message={queryRoleMenusByIdQuery.error} />;
  }

  return <AlertLoad />;
}
